const path = require('path')

global.service_caches = {}

// 存储全局验证函数
global.servive_auth_fn = null

// 服务调用
function Invocation(serviceName, actionName, serviveModule, originFunc) {
    return function () {
        const originArguments = arguments
        return function (req, res, next) {
            if (global.servive_auth_fn) {
                // 校验全局权限
                global.servive_auth_fn(req, res,next, serviceName, actionName, function (pass) {
                    if (pass) {
                        originFunc.apply(serviveModule, originArguments)
                    } else {
                        res.sendResult(null, 401, '权限验证失败')
                    }
                })
            } else {
                res.sendResult(null, 401, '权限验证失败')
            }
        }
    }
}

// 获取服务对象
module.exports.getService = function (serviceName) {
    if (global.service_caches[serviceName]) {
        return global.service_caches[serviceName]
    }
    const servicePath = path.join(process.cwd(), 'services', serviceName)
    const serviceModule = require(servicePath)
    if (!serviceModule) {
        console.log(`${serviceName}模块没有被发现`)
        return null
    }
    console.log(`正在调用${serviceName}服务`)
    global.service_caches[serviceName] = {}

    for (actionName in serviceModule) {
        if (serviceModule && serviceModule[actionName] && typeof(serviceModule[actionName]) == 'function' ) {
            const originFunc = serviceModule[actionName]
            global.service_caches[serviceName][actionName] = Invocation(serviceName, actionName, serviceModule, originFunc)
        }
    }
    return global.service_caches[serviceName]
}

// 设置全局验证函数
module.exports.setAuthFn = function (authFn) {
    global.servive_auth_fn = authFn
}